package com.cskt.petoms.service.impl;

import com.cskt.common.constants.Constants;
import com.cskt.common.entity.pojo.Cart;
import com.cskt.common.entity.pojo.Sku;
import com.cskt.common.entity.vo.ResultVO;
import com.cskt.common.utils.RedisKeyUtils;
import com.cskt.petoms.service.CartService;
import com.cskt.petoms.service.redis.RedisService;
import com.cskt.petoms.service.remote.RemoteProductService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 购物车service层实现
 *
 * @author admin
 **/
@Service
public class CartServiceImpl implements CartService {
    private static final Logger log = LoggerFactory.getLogger(CartServiceImpl.class);
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private RemoteProductService productService;

    @Override
    public boolean addCart(Long skuId, Integer num, Long userId) {
        try {
            Cart cart = new Cart();

            String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_CART, userId.toString());
            Map<String, String> value = redisService.getHashValues(key);
            //判断当前商品在购物车中是否存在，如果存在，则在原有的基础上增加数量
            if (ObjectUtils.isEmpty(value)) {

                //数据封装
                cart = skuToCart(skuId, num);
            } else {
                //    如果存在商品，则针对每一件商品做处理
                for (String cartKey : value.keySet()) {
                    if (cartKey.equals(skuId.toString())) {
                        //    如果当前skuId对应的商品在购物车中已经存在，则累加数量和金额
                        try {
                            cart = objectMapper.readValue(value.get(cartKey), Cart.class);
                        } catch (JsonProcessingException e) {
                            log.error("反序列化异常");
                        }
                        cart.setNum(cart.getNum() + num);
                        cart.setPrice(cart.getPrice().add(cart.getUnitPrice().multiply(BigDecimal.valueOf(num))));
                    } else {
                        cart = skuToCart(skuId, num);
                    }
                }
            }
            redisService.putHash(key, cart.getSkuId().toString(), objectMapper.writeValueAsString(cart));
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将sku转换成为cart
     *
     * @param skuId
     * @param num
     */
    private Cart skuToCart(Long skuId, Integer num) {
        //如果当前商品sku在购物车中不存在，则需要获取商品相关信息
        // 先根据skuid查询商品信息，商品不在当前模块，所以要开始通过spring cloud实现远程调用
        ResultVO<Sku> resultVO = productService.getSkuById(skuId);
        Sku sku = resultVO.getData();
        //Sku sku = productService.getSkuBySKuId(skuId).getData();
        Cart cart = new Cart();
        //数据封装
        BeanUtils.copyProperties(sku, cart);
        //设置其他数据
        cart.setSkuId(skuId);
        cart.setAddTime(LocalDateTime.now());
        cart.setNum(num);
        //计算当前商品的总价
        BigDecimal price = sku.getPrice().multiply(BigDecimal.valueOf(num));
        cart.setPrice(price);
        cart.setUnitPrice(sku.getPrice());

        return cart;
    }

}
